<!DOCTYPE html>
<html>

<head>
  <title>WebSocket 示例</title>
</head>

<body>
  <h1>WebSocket 示例</h1>

  <button id="connectBtn">连接 WebSocket</button>
  <button id="sendBtn" disabled>发送消息</button>

  <script>
    const connectBtn = document.getElementById('connectBtn');
    const sendBtn = document.getElementById('sendBtn');
    let socket;

    // 创建 WebSocket 连接
    function connectWebSocket() {
      socket = new WebSocket('ws://localhost:1427');

      // 连接成功时触发
      socket.onopen = function (event) {
        console.log('WebSocket 已连接');
        connectBtn.disabled = true;
        sendBtn.disabled = false;
      };

      // 接收到消息时触发
      socket.onmessage = function (event) {
        console.log('收到消息:', event.data);
      };

      // 连接关闭时触发
      socket.onclose = function (event) {
        console.log('WebSocket 已关闭');
        connectBtn.disabled = false;
        sendBtn.disabled = true;
      };
    }

    // 发送消息
    function sendMessage() {
      const params = JSON.stringify(
        {
          type: 'initRequestData',
          data: [
            {
              "htmlStr": '<!DOCTYPE html><html><head><title>HTML Table Example</title></head><body><h1>Example Table</h1><table border="1"><thead><tr><th>Name</th><th>Age</th><th>Occupation</th></tr></thead><tbody><tr><td>John Doe</td><td>30</td><td>Engineer</td></tr><tr><td>Jane Smith</td><td>25</td><td>Teacher</td></tr><tr><td>Michael Johnson</td><td>40</td><td>Doctor</td></tr></tbody></table></body></html>',
              "printer": "皓诚达打印机",
            },
          ]

        }
      )
      socket.send(params);
    }

    // 绑定按钮点击事件
    connectBtn.addEventListener('click', connectWebSocket);
    sendBtn.addEventListener('click', sendMessage);
  </script>
</body>

</html>